import { Directive, HostListener, Renderer2, ElementRef, Input } from '@angular/core';
import {DragDropService} from "./drag-drop.service";
//todo 都需要改动
@Directive({
  selector: '[app-draggable][draggedClass]'
})
export class DragDirective {
  // 是否可以拖动
  private _isDraggble = false;
  /**
   * 属性方法
   * 调用输入属性就会传入过来
   * @param val
   */
  @Input('app-draggable')
  set isDraggable(val: boolean){
    this._isDraggble = val;
    // 设置是否可以拖动
    this.rd.setAttribute(this.el.nativeElement,'draggable',`${val}`)
  }
  get isDraggable(){
    return this._isDraggble;
  }
  // 接收需要添加的class名称
  @Input()draggedClass:string;
  // 唯一标识
  @Input() dragTag: string;
  // 传递的数据
  @Input() dragData: any;
  constructor(private el: ElementRef,
              private rd: Renderer2,
              private service:DragDropService) { }

  // 开始拖
  @HostListener('dragstart',['$event'])
  onDragstart(ev:Event){
    if(this.el.nativeElement === ev.target){
      this.rd.addClass(this.el.nativeElement,this.draggedClass);
      // 传递数据
      this.service.setDragData({tag:this.dragTag, data:this.dragData})
    }
  }
  // 放
  @HostListener('dragend',['$event'])
  onDragendt(ev:Event){
    if(this.el.nativeElement === ev.target){
      this.rd.removeClass(this.el.nativeElement,this.draggedClass)
    }
  }

}
